<template>
  <view class="loading-container">
		<view class="bg">
			<image src="/static/loading-bg.png" mode="aspectFit"></image>
		</view>
		<view class="footer">
			<image src="/static/lvgang.png" mode="aspectFit"></image>
			<text style="margin-bottom: 10rpx;">江苏绿港现代农业发展股份有限公司</text>
			<up-loading-icon color="#43C679" :size="28"></up-loading-icon>
		</view>

		<!-- 更新 -->
    <!-- #ifdef APP-PLUS -->
      <upVersion :upLoadUrl="upLoadUrl" :newVision="newVision" :appStoreUrl='appStoreUrl' :show="show" :log="log" @close="close"></upVersion>
    <!-- #endif -->

    <!-- #ifdef H5 -->
      <hwUpVersion  :newVision="hwnewVision"  :show="hwshow" :log="hwlog"></hwUpVersion>
    <!-- #endif -->
  </view>
</template>

<script>
import { useUserStore } from '@/pinia-store/user';
import { useLoginStore, useStartTodoPolling } from "@/pinia-store/user.js";
import { SysUser } from '@/utils/sql/user.js';
import { ChatSql } from '@/utils/sql/chat.js';
import { compareVersions } from '@/utils/tools.js'
import upVersion from "@/components/as-upVersion/as-upVersion.vue"
import hwUpVersion from "@/components/as-upVersion/hw-upVersion.vue";
import { COMMON_API_BASE_URL } from '@/utils/request.js'

export default {
  name: 'loading',
	components: {
		upVersion,
    hwUpVersion
	},
  data () {
    return {
			// 更新参数
			newVision: 0, //版本号
			upLoadUrl: '', //下载地址
			appStoreUrl: '', //下载地址
			log: '', //备注
			show: false, // 展示更新

      hwnewVision: 0, // h5版本号
      hwlog: '', //备注
      hwshow: false, // h5展示更新
    }
  },
	created() {
	  if(uni.getSystemInfoSync().uniPlatform == 'web'){
	    if(!uni.getStorageSync('token') && !uni.getStorageSync('user')){
				this.redirect("/pages/user/login");
	    }else {
				this.redirect("/pages/chat/list/index");
			}
	  }

		// 判断有没有存储权限
		// #ifdef APP-PLUS

		var _this = this
		plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'], function(e) {
			if (e.deniedAlways.length > 0) { //权限被永久拒绝
				// 弹出提示框解释为何需要读写手机储存权限，引导用户打开设置页面开启
				uni.showModal({
					title: '存储权限',
					content: '您拒绝了存储权限，请去设置-应用开启存储权限。',
					success: function (res) {
						if (res.confirm) {
							// 用户点击确定 执行登录流程
						} else if (res.cancel) {
							// 用户点击取消 提示必须授权
						}
					}
				});
			}
			if (e.deniedPresent.length > 0) { //权限被临时拒绝
				// 弹出提示框解释为何需要读写手机储存权限，可再次调用plus.android.requestPermissions申请权限
				plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'])
			}
			if (e.granted.length > 0) { //权限被允许
				// 调用依赖获取读写手机储存权限的代码
				// 获取权限成功之后调用的函数

				// 获取登录信息
				SysUser.init().then(init => {
					// 创建聊天相关
					ChatSql.createChatTable();

					if(init.length === 0) {
						console.log('无登录信息');
						_this.redirect("/pages/user/login");
					}else {
						// 用户信息写入缓存
						const userStore = useUserStore();
						userStore.setUser(init[0]);
						// token
						const loginStore = useLoginStore();
						loginStore.login(init[0].token);
						uni.$emit('initJpush', init[0].phone)
						_this.redirect("/pages/chat/list/index");
					}
				}).catch(initErr => {
					console.log('初始化SQlite失败', initErr);
					_this.redirect("/pages/user/login");
				})
			}
		}, function(e) {
			// console.log('R12133313221' + JSON.stringify(e));
		});
		// #endif
    this.Timingmarkers()
	},
  methods: {
		/**
		 * 获取版本
		 */
		checkVersion(callback) {
			var info = uni.getSystemInfoSync();
			uni.request({
				url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/index/Index/get_new_version`, //仅为示例，并非真实接口地址。
				header: {
					'content-type': 'application/json'
				},
				method: 'POST',
				dataType: 'json',
				success: (res) => {
					//回调赋值
					if(res.data.data.code === 0){
						return;
					}

          let version
          // #ifdef H5
          version = uni.getStorageSync('localVersion') || info?.appVersion
          // #endif

          // #ifdef APP-PLUS
          version = info.appWgtVersion
          // #endif

					if(compareVersions(version, res.data.data.version_no) === -1) {
            // #ifdef APP-PLUS
              this.newVision = res.data.data.version_no
              this.upLoadUrl = "https://cloud.mfarmers.com"+res.data.data.url
              this.log = res.data.data.remark
              this.show = true
            // #endif


            // #ifdef H5
            this.hwnewVision = res.data.data.version_no
            this.hwlog = res.data.data.remark
            this.hwshow = true
            // #endif
					}else {
						callback();
					}
				}
			});
		},
		redirect(url) {
			// #ifdef APP
			this.checkVersion(() => {
				setTimeout(() => {
					uni.reLaunch({
						url: url
					})
				}, 1500)
			});
			// #endif

			// #ifdef H5
			// setTimeout(() => {
			// 	uni.reLaunch({
			// 		url: url
			// 	})
			// }, 1500)

      this.checkVersion(() => {
        setTimeout(() => {
          uni.reLaunch({
            url: url
          })
        }, 1500)
      });

			// #endif
		},
    Timingmarkers(){
      const pollingStore = useStartTodoPolling();
      pollingStore.start();
    },
    close(){
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.loading-container {
  position: relative;
  width: 100vw;
  height: 100vh;
	background-color: #fff;
	.bg {
		margin-top: 200rpx;
		display: flex;
		justify-content: center;
		image {
			height: 720rpx;
		}
	}
	.footer {
		position: fixed;
		width: 100%;
		bottom: 50rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		image {
			height: 80rpx;
			margin-bottom: 18rpx;
		}
	}
}
</style>
